//
//  MVVM_BaseViewModel.swift
//  MVVM_BaseViewController
//
//  Created by alyadan on 2016/10/13.
//  Copyright © 2016年 alyadan. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift

open class MVVM_BaseViewModel: NSObject {
    
    public var disposeBag = DisposeBag()
    weak public var parentViewModel: MVVM_BaseViewModel?
    
    public weak var MVVM_modelController: UIViewController?
    
    public var MVVM_navigationController: UINavigationController? {
        return self.findNavigation()
    }
    
    func findNavigation() -> UINavigationController? {
        if let nav = modelController_calc?.navigationController {
            return nav
        }
        
        return parentViewModel?.MVVM_navigationController
    }
    
    
    public var modelController_calc: UIViewController? {
        get {
            if !(self.isKind(of: MVVM_BaseVCModel.self)), let x = parentViewModel {
                return x.modelController_calc
            }
            
            return MVVM_modelController
        }
    }
    
    public init(parentViewModel:MVVM_BaseViewModel? = nil){
        super.init()
        self.parentViewModel = parentViewModel
        //        if let x = parentViewModel {
        //            if !x.isKind(of: MVVM_BaseVCModel.self) {
        //                x.rx.observeWeakly(UIViewController.self, "MVVM_modelController").bind(onNext: {[unowned self] (vc:UIViewController?) in
        //                    self.MVVM_modelController = vc
        //                }).addDisposableTo(disposeBag)
        //            }
        //        }
        
        setupModel()
    }
    
    open func setupModel(){}
    open func bindDataModel(){}
    
    deinit {
        print("\(self) deinit")
    }
    
    public func findValidVCModel() -> MVVM_BaseVCModel? {
        
        var validVCModel: MVVM_BaseViewModel?
        
        validVCModel = self.parentViewModel
        
        while validVCModel != nil && !(validVCModel!.isKind(of: MVVM_BaseVCModel.self))  {
            validVCModel = validVCModel!.parentViewModel
        }
        
        return validVCModel as? MVVM_BaseVCModel
    }
    
}
